/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

function dataOnTheFly_onScreenReadyNewCourse(element) {
    // Make the proper activity indicator appear
    if (bb.device.isBB10) {
        element.getElementById('bb7Loading').style.display = 'none';
    } else {
        element.getElementById('bb10Loading').style.display = 'none';
    }
}

function dataOnTheFly_initialLoadNewCourse(element) {
        
    var  option, addPanel = document.getElementById('addPanel');
    // Create our list item
    //DivCourseName
    divCourseName = document.createElement('div');
    divCourseName.innerHTML = 'Course Name :';
    addPanel.appendChild(divCourseName);

    //Input CourseName
    inputCourseName = document.createElement('input');
    inputCourseName.setAttribute('id', 'inputCourseName');
    addPanel.appendChild(inputCourseName);
    inputCourseName = bb.textInput.style(inputCourseName);

    //Div Credits
    divCredit = document.createElement('div');
    divCredit.innerHTML = 'Credits :';
    addPanel.appendChild(divCredit);

    //Input Credits
    inputCredit = document.createElement('input');
    inputCredit.setAttribute('id', 'inputCredit');
    addPanel.appendChild(inputCredit);
    inputCredit = bb.textInput.style(inputCredit);

    //Div Year
    divYear = document.createElement('div');
    divYear.innerHTML = 'Year :';
    addPanel.appendChild(divYear);

    //Input Year
    inputYear = document.createElement('input');
    inputYear.setAttribute('id', 'inputYear');
    addPanel.appendChild(inputYear);
    inputYear = bb.textInput.style(inputYear);

    //Div Term
    divTerm = document.createElement('div');
    divTerm.innerHTML = 'Term :';
    addPanel.appendChild(divTerm);

    // Div Select Term
    dropdownTerm = document.createElement('select');
    dropdownTerm.setAttribute('data-bb-style', 'stretch');
    dropdownTerm.setAttribute('id', 'inputTermOption');
    option = document.createElement('option');
    option.setAttribute('value',JSON.parse(localStorage.getItem('jSettingTerm'))[0].seasonal1);
    option.setAttribute('selected','selected');
    option.innerHTML = JSON.parse(localStorage.getItem('jSettingTerm'))[0].seasonal1;
    dropdownTerm.appendChild(option);
    option = document.createElement('option');
    option.setAttribute('value',JSON.parse(localStorage.getItem('jSettingTerm'))[0].seasonal2);
    option.innerHTML = JSON.parse(localStorage.getItem('jSettingTerm'))[0].seasonal2;
    dropdownTerm.appendChild(option);
    option = document.createElement('option');
    option.setAttribute('value',JSON.parse(localStorage.getItem('jSettingTerm'))[0].seasonal3);
    option.innerHTML = JSON.parse(localStorage.getItem('jSettingTerm'))[0].seasonal3;
    dropdownTerm.appendChild(option);
    option = document.createElement('option');
    option.setAttribute('value',JSON.parse(localStorage.getItem('jSettingTerm'))[0].seasonal4);
    option.innerHTML = JSON.parse(localStorage.getItem('jSettingTerm'))[0].seasonal4;
    dropdownTerm.appendChild(option);
    // Apply the styling
    dropdownTerm = bb.dropdown.style(dropdownTerm);
    // Append the item
    addPanel.appendChild(dropdownTerm);

    //Div Grade
    divGrade = document.createElement('div');
    divGrade.innerHTML = 'Grade :';
    addPanel.appendChild(divGrade);

    // Div Select Term
    dropdownGrade = document.createElement('select');
    dropdownGrade.setAttribute('data-bb-style', 'stretch');
    dropdownGrade.setAttribute('id', 'inputGrade');
    option = document.createElement('option');
    option.setAttribute('value', 'A+');
    option.setAttribute('selected','selected');
    option.innerHTML = "A+";
    dropdownGrade.appendChild(option);
    option = document.createElement('option');
    option.setAttribute('value', 'A');
    option.innerHTML = "A";
    dropdownGrade.appendChild(option);
    option = document.createElement('option');
    option.setAttribute('value', 'A-');
    option.innerHTML = "A-";
    dropdownGrade.appendChild(option);
    option = document.createElement('option');
    option.setAttribute('value', 'B+');
    option.innerHTML = "B+";
    dropdownGrade.appendChild(option);
    option = document.createElement('option');
    option.setAttribute('value', 'B');
    option.innerHTML = "B";
    dropdownGrade.appendChild(option);
    option = document.createElement('option');
    option.setAttribute('value', 'C+');
    option.innerHTML = "C+";
    dropdownGrade.appendChild(option);
    option = document.createElement('option');
    option.setAttribute('value', 'C');
    option.innerHTML = "C";
    dropdownGrade.appendChild(option);
    option = document.createElement('option');
    option.setAttribute('value','D');
    option.innerHTML = "D";
    dropdownGrade.appendChild(option);
    option = document.createElement('option');
    option.setAttribute('value', 'E');
    option.innerHTML = "E";
    dropdownGrade.appendChild(option);
    option = document.createElement('option');
    option.setAttribute('value', 'F');
    option.innerHTML = "F";
    dropdownGrade.appendChild(option);
    // Apply the styling
    dropdownGrade = bb.dropdown.style(dropdownGrade);
    // Append the item
    addPanel.appendChild(dropdownGrade);


    //Button Add New Course
    buttonAdd = document.createElement('div');
    buttonAdd.innerHTML = 'Add Course';
    buttonAdd.setAttribute('data-bb-type', 'button');
    buttonAdd.setAttribute('data-bb-style', 'stretch');
    buttonAdd.setAttribute('onclick', "saveCourse();");
    buttonAdd = bb.button.style(buttonAdd);
    addPanel.appendChild(buttonAdd);


    // re-compute the scrolling area
    if (bb.scroller) {
        bb.scroller.refresh();
    }
    // Remove our waiting and refresh the list
    document.getElementById('waiting').style.display = 'none';
    dataList.refresh(items);
}
//append jsonObject2 to last element of jsonObject1
function appendNewData (jsonObject1, jsonObject2){
    //get object from local json storage
    json1 = JSON.parse(JSON.stringify(jsonObject1));
    json2 = JSON.parse(JSON.stringify(jsonObject2));
    
    // concate new json object
    json1 = json1.concat(json2);
    localStorage.setItem(sessionStorage.getItem('tempJName'), JSON.stringify(json1));
}

//==============================================================================
// Add new course
function saveCourse(){
    var courseName = document.getElementById('inputCourseName').value;
    var credit = parseInt(document.getElementById('inputCredit').value);
    var year = parseInt(document.getElementById('inputYear').value);
    var term = document.getElementById('inputTermOption').value;
    var grade = document.getElementById('inputGrade').value;
    var semesterName = year + "-"+term;

    //check existing semester name
    if (localStorage.getItem(semesterName) === null){
        localStorage.setItem(semesterName, JSON.stringify([{
            courseName: courseName,
            credit: credit,
            year: year,
            term: term,
            grade: grade
        }])); 
    }
    //append new element
    else {
        // local storage
        jName = JSON.parse(localStorage.getItem(semesterName));
        // new item 
        jName2 ={
            courseName: courseName, 
            credit: credit, 
            year: year, 
            term: term, 
            grade: grade
        };

        //store temporary primary jName to tempJName
        sessionStorage.setItem('tempJName', semesterName);
        // call function appendNewData
        appendNewData(jName, jName2);
    }
    updateInsertSemesterRecap(semesterName, grade, credit);
    updateInsertGPARecap();
    
    alert("Add Course Successful!");
}

// Update Semester for New inserted instance
function updateInsertSemesterRecap(semesterName, grade, credit){
    var json = JSON.parse(localStorage.getItem('jSemesterRecap'));
    var count = 0;
    var found = false;
    //insert new first element
    if (localStorage.getItem('jSemesterRecap')== null){
        localStorage.setItem('jSemesterRecap', JSON.stringify([{
            semesterName: semesterName,
            gpaSemester: localStorage.getItem(grade),
            totalCredit: credit,
            numberOfCourse: '1'
        }]));
        found = true;
    }
    // jSemester recap already exist
    else{
        for(var i=0; i<json.length; i++) { 
            if(json[i].semesterName == semesterName) {
                //getCurrent value
                var curGpa = parseFloat(json[i].gpaSemester);
                var totalCredit = parseInt(json[i].totalCredit);
                var gradeNew = parseInt(localStorage.getItem(grade));
                var creditNew = parseInt(credit);

                //update gpasemester, total credit, and number of course
                json[i].gpaSemester =(((curGpa*totalCredit)+(gradeNew*creditNew))/(totalCredit + creditNew));
                json[i].gpaSemester = parseFloat(json[i].gpaSemester.toFixed(2));
                json[i].totalCredit = totalCredit + creditNew;
                json[i].numberOfCourse++;
                localStorage.setItem('jSemesterRecap', JSON.stringify(json));
                found = true;
                break;
            }
        } 
    }
    if (found == false) {
        //append new data
        jName = JSON.parse(localStorage.getItem('jSemesterRecap'));
        // new item 
        jName2 =[{
            semesterName: semesterName,
            gpaSemester: localStorage.getItem(grade),
            totalCredit: credit,
            numberOfCourse: '1'
        }];
        //store temporary primary jName to tempJName
        sessionStorage.setItem('tempJName', 'jSemesterRecap');
        // call function appendNewData
        appendNewData(jName, jName2);
    }
}

function updateInsertGPARecap(){
//recalculate update from jSemesterRecap
//Iterate jSemesterRecap
// GPATotal = Sum ( (totalcredit/sumOfTotalCredit)* GPA Semester)
    var json = JSON.parse(localStorage.getItem('jSemesterRecap'));   
    var cumulativeEnumerator = 0;
    var cumulativeCredit = 0;
    var cumulativeSemester = 0;
    var cumulativeCourse =0;
    for(var i=0; i<json.length; i++) { 
        cumulativeEnumerator = parseFloat(cumulativeEnumerator + (json[i].gpaSemester*json[i].totalCredit));
        cumulativeCredit = parseInt(cumulativeCredit + json[i].totalCredit);
        cumulativeCourse = parseInt(cumulativeCourse + parseInt(json[i].numberOfCourse));
    }
    // cumulative semester is the length of jSemesterRecap
    cumulativeSemester = i;
    if (localStorage.getItem('jGPARecap')== null){
        localStorage.setItem('jGPARecap', JSON.stringify([{
            gpaTotal: parseFloat((cumulativeEnumerator/cumulativeCredit).toFixed(2)),
            semesterTotal: cumulativeSemester,
            creditTotal: cumulativeCredit,
            courseTotal: cumulativeCourse
        }]));
    }
    else {
        var jsonGPA = JSON.parse(localStorage.getItem('jGPARecap'));
        jsonGPA[0].gpaTotal = parseFloat((cumulativeEnumerator/cumulativeCredit).toFixed(2));
        jsonGPA[0].semesterTotal = cumulativeSemester;
        jsonGPA[0].creditTotal = cumulativeCredit;
        jsonGPA[0].courseTotal = cumulativeCourse;
        //set new value
        localStorage.setItem('jGPARecap', JSON.stringify(jsonGPA));
    }
}

function initializationNewSemesterRecap(){
    localStorage.setItem('jSemesterRecap', JSON.stringify([{
        semesterName: '2011-Spring',
        gpaSemester: '3.5',
        totalCredit: '100',
        numberOfCourse: '40'
    }]));
/*
    var ambitionRes = JSON.parse(localStorage.getItem('jGPAAmbition'));
    alert(ambitionRes[0].ambitionResult);
    var gpaResult = ambitionRes[0].ambitionResult;
    document.getElementById('gpaAmbitionResult').innerHTML = gpaResult;
    */
}


function semesterRecapUpdate(semesterName, credit, grade){
    //check existing
    var json = JSON.parse(localStorage["jSemesterRecap"]);
    var gpaSemester = getGPASemesterBySemesterName(json, semesterName);
    
    //new data update didnt exist
    if (gpaSemester == null){
        //calculate GPA first
        gradeConvert = parseFloat(localStorage.getItem(grade));
        alert('grade Convert Result = '+ gradeConvert);
        
    // append new semester data
    //set numberOfCourse = 1
        
    }
}


function fillOptionSelect() {
    alert(localStorage.getItem('A+'));
    
/*
    var grade = ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D', 'E', 'F'];
    var gradeList = document.getElementById ("inputGrade");
    // Option (text, value)
    var gradeOption1 = new Option ("grade[0]", "grade[0]");
    gradeList.options.add (gradeOption1);
    var gradeOption = new Option ('grade[1]','grade[1]');
    gradeList.options.add (gradeOption);

    alert(localStorage.getItem('A+'));
    */
   
}

function deleteCourse(){
    localStorage.setItem('A+', '4.33');
    localStorage.setItem('A', '4');
	
    alert(localStorage.getItem('A+'));
/*
    var parsed = JSON.parse(localStorage.getItem('2011-Spring'));
    alert("Object length = "+JSON.parse(localStorage.getItem('2011-Spring'))[0].courseName);
    JSON.parse(localStorage.getItem('2011-Spring'))[0].courseName = "TA-3";
    alert("Object length = "+JSON.parse(localStorage.getItem('2011-Spring'))[0].courseName);
    */
//localStorage.removeItem('semesterName');
/*
    localStorage.setItem('jSemesterRecap', JSON.stringify([{
        semesterName: '2011-Spring',
        gpaSemester: '3.5',
        totalCredit: '100',
        numberOfCourse: '40'
        },
    {
        semesterName: '2012-Spring',
        gpaSemester: '3',
        totalCredit: '133',
        numberOfCourse: '13'
        }]));
    */
    
//var json = JSON.parse(localStorage["jSemesterRecap"]);
//var href = getItemHrefById(json, "2011-Spring");
// alert('current GPA semester'+href);

//update set jSemesterRecap gpaSemester 
//setItemHrefById(json, '2011-Spring', '3.1');
//var href = getItemHrefById(json, "2011-Spring");
//alert('New Gpa Semester'+href);
      
   
// update storage:
//deleteItemById(json, '2011-Spring');
//localStorage["jSemesterRecap"] = JSON.stringify(json);
    
//var json = JSON.parse(localStorage["jSemesterRecap"]);
//var href = getItemHrefById(json, "2011-Spring");
//alert('current GPA semester'+href);
}

